
#include "graphics/morpher.h"
#include "graphics/node.h"
#include "graphics/mesh.h"
#include "graphics/renderer.h"

namespace dw
{ 
	namespace graphics
	{

		MorphController::MorphController()
		{
		}

		MorphController::~MorphController()
		{
		}

		Node* MorphController::getTarget(const uint32 target) const
		{
			if (target > static_cast< uint32 >(_targets.size()) - 1)
				throw std::out_of_range("target");
			return _targets[target];
		}

		void MorphController::update(const float& t)
		{
			if (!_node)
				throw std::runtime_error(__FUNCTION__);

			Object* object = _node->getObject();

			if (!object || object->getType() != Object::MESH)
				throw std::runtime_error(__FUNCTION__);

			/*
			Mesh* mesh									= static_cast< Mesh* >(object);
			VertexBuffer* vertexBuffer	= mesh->getVertexBuffer();

			// lock the mesh vb and the morph targets vb 
			vertexBuffer->lock(0 , 0, IBuffer::BA_READ_WRITE);

            unsigned int i, j;

			for (i = 0; i < _targets.size(); ++i)
			{
				Mesh* targetMesh					= static_cast< Mesh* >(_targets[i]->getObject());
				VertexBuffer* targetVertexBuffer	= targetMesh->getVertexBuffer();

				targetVertexBuffer->lock(0, 0, IBuffer::BA_READ_ONLY);
			}

			for (i = 0; i < vertexBuffer->getNumVertices(); ++i)
			{
				Point3f vertex	= vertexBuffer->getVertex(i);
				Vector3f delta		= Vector3f::zero;

				for (j = 0; j < _targets.size(); ++j)
				{
					Mesh* targetMesh					= static_cast< Mesh* >(_targets[j]->getObject());
					VertexBuffer* targetVertexBuffer	= targetMesh->getVertexBuffer();

					delta += (vertex - targetVertexBuffer->getVertex(i)) * _weights[j];
				}
				vertex += delta;
				vertexBuffer->setVertex(j, vertex);
			}

			// unlock the mesh vb and the morph targets vb 
			for (unsigned i = 0; i < _targets.size(); ++i)
			{
				Mesh* targetMesh					= static_cast< Mesh* >(_targets[i]->getObject());
				VertexBuffer* targetVertexBuffer	= targetMesh->getVertexBuffer();

				targetVertexBuffer->unlock();
			}

			vertexBuffer->unlock();	
			*/
		}

	} // namespace graphics
} // namespace dw